/**
 * 报关单相关API调用
 */
import axiosInstance from './axios';
import type { ApiResponse, ExtractionResponse, FieldRule } from '../types/customs';

/**
 * 健康检查
 */
export const healthCheck = async (): Promise<ApiResponse> => {
  const response = await axiosInstance.get('/health');
  return response.data;
};

/**
 * 上传文件并提取字段
 */
export const extractFields = async (files: File[]): Promise<ExtractionResponse> => {
  const formData = new FormData();
  files.forEach((file) => {
    formData.append('files', file);
  });

  const response = await axiosInstance.post('/api/v1/extract', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });

  return response.data;
};

/**
 * 下载Excel文件（重新提取，慢）
 * @deprecated 建议使用 exportExcelFromData
 */
export const downloadExcel = async (files: File[]): Promise<Blob> => {
  const formData = new FormData();
  files.forEach((file) => {
    formData.append('files', file);
  });

  const response = await axiosInstance.post('/api/v1/extract/download', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    responseType: 'blob',
  });

  return response.data;
};

/**
 * 从已提取的数据导出Excel（快速）
 */
export const exportExcelFromData = async (
  fieldsData: Record<string, any>,
  filenamePrefix?: string
): Promise<Blob> => {
  const response = await axiosInstance.post(
    '/api/v1/export/excel',
    {
      fields_data: fieldsData,
      filename_prefix: filenamePrefix || '报关单',
    },
    {
      responseType: 'blob',
    }
  );

  return response.data;
};

/**
 * 获取提取规则列表
 */
export const getExtractionRules = async (): Promise<ApiResponse<FieldRule[]>> => {
  const response = await axiosInstance.get('/api/v1/test/rules');
  return response.data;
};

